import React, { useState, useContext, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Alert,
  ScrollView,
  ActivityIndicator,
  Modal,
} from "react-native";
import ShowEssayQues from "../../components/showSubject/ShowEssayQues";
import ProblemContext from "../../context/questionnaire/ProblemContext";

import { FontAwesome } from "@expo/vector-icons";

const Loading = ({ text }) => {
  return (
    <View style={styles.alterView}>
      <ActivityIndicator animating={true} size={"large"} color="#bbb" />
      <Text style={{ color: "#aaa", marginTop: 10 }}>{text}</Text>
    </View>
  );
};

const Error = () => {
  <View style={styles.alterView}>
    <Text style={{ color: "#aaa", marginTop: 10 }}>出错了...</Text>
  </View>;
};

const AddProblem = ({ navigation }) => {
  const { problemLoading, ProblemData, editProblem, updataProblem } =
    useContext(ProblemContext);
  console.log("问题清单---", ProblemData.problem);
  // 描述性问题
  const [problem0, setProblem0] = useState([]);
  // 细节性问题
  const [problem1, setProblem1] = useState([]);

  useEffect(() => {
    setProblem0(ProblemData.problem[0]);
    setProblem1(ProblemData.problem[1]);
  }, [ProblemData]);

  const [isEditing, setIsEditing] = useState(false);

  const updateProAlter = () => {
    Alert.alert("", "是否更新问题清单？", [
      {
        text: "取消",
      },
      {
        text: "确定",
        onPress: () => handleUpdatePro(),
      },
    ]);
  };
  const handleUpdatePro = async () => {
    setIsEditing(true);
    try {
      await updataProblem();
      Alert.alert("更新问卷模板成功");
    } catch (error) {
      console.log(error);
      Alert.alert("更新问卷模板失败");
    }
    setIsEditing(false);
    navigation.goBack();
  };

  React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity
          onPress={async () => {
            updateProAlter();
          }}
        >
          <View style={{ marginRight: 10 }}>
            <FontAwesome name="save" size={22} color="#fff" />
          </View>
        </TouchableOpacity>
      ),
    });
  }, [navigation]);

  let t_addIndex = 0;

  // 添加题目
  const onSubmit = async (index, question) => {
    let t_problem0 = problem0,
      t_problem1 = problem1;
    if (t_addIndex == 0) {
      t_problem0.push(question);
      setProblem0((preProblem) => {
        return [...preProblem, question];
      });
    } else if (t_addIndex == 1) {
      t_problem1.push(question);
      setProblem1((preProblem) => {
        return [...preProblem, question];
      });
    }
    editProblem(t_problem0, t_problem1);
  };

  // 修改题目
  const onEdit = async (index, question) => {
    let t_problem0 = problem0,
      t_problem1 = problem1;
    if (t_addIndex == 0) {
      t_problem0[index] = question;
      await setProblem0((preProblem) => {
        return preProblem.map((preQues, preIndex) => {
          return index == preIndex ? question : preQues;
        });
      });
    } else if (t_addIndex == 1) {
      t_problem1[index] = question;
      await setProblem1((preProblem) => {
        return preProblem.map((preQues, preIndex) => {
          return index == preIndex ? question : preQues;
        });
      });
    }
    console.log("编辑问题---", t_problem0, t_problem1);
    editProblem(t_problem0, t_problem1);
  };

  // 删除题目
  const onDelete = async (index) => {
    // console.log("删除---", t_addIndex);
    let t_problem0 = problem0,
      t_problem1 = problem1;
    if (t_addIndex == 0) {
      t_problem0.splice(index, 1);
      await setProblem0((preProblem) => {
        return preProblem.filter((item, proIndex) => index !== proIndex);
      });
    } else if (t_addIndex == 1) {
      t_problem1.splice(index, 1);
      await setProblem1((preProblem) => {
        return preProblem.filter((item, proIndex) => index !== proIndex);
      });
    }
    console.log("删除完问题---", problem0, problem1);
    editProblem(problem0, problem1);
  };

  return (
    <View style={styles.container}>
      {problemLoading == "ing" ? (
        <Loading text="Loading..."></Loading>
      ) : (
        <View style={{ height: "100%" }}>
          <View style={{ flex: 10 }}>
            <ScrollView>
              <View>
                <View
                  style={{
                    alignItems: "center",
                    marginTop: 15,
                    marginBottom: 5,
                  }}
                >
                  <Text style={{ fontWeight: "bold", fontSize: 17 }}>
                    描述问题
                  </Text>
                </View>
                {problem0.map((problem, index) => {
                  return (
                    <View key={index}>
                      <TouchableOpacity
                        onPress={() => {
                          t_addIndex = 0;
                          navigation.navigate("添加题目", {
                            onSubmit: onEdit,
                            onDelete: onDelete,
                            isAdd: false,
                            type: 1,
                            quesIndex: index,
                            showQues: problem,
                          });
                        }}
                      >
                        <ShowEssayQues
                          isEdit={false}
                          number=""
                          QuesContent={problem}
                        ></ShowEssayQues>
                      </TouchableOpacity>
                    </View>
                  );
                })}
                <View
                  style={{
                    alignItems: "center",
                    marginTop: 20,
                    marginBottom: 5,
                  }}
                >
                  <Text style={{ fontWeight: "bold", fontSize: 17 }}>
                    细节问题
                  </Text>
                </View>
                {problem1.map((problem, index) => {
                  if (problem.type == 1) {
                    return (
                      <View key={index}>
                        <TouchableOpacity
                          onPress={() => {
                            t_addIndex = 1;
                            navigation.navigate("添加题目", {
                              onSubmit: onEdit,
                              onDelete: onDelete,
                              isAdd: false,
                              type: 1,
                              quesIndex: index,
                              showQues: problem,
                            });
                          }}
                        >
                          <ShowEssayQues
                            isEdit={false}
                            number={index + 1}
                            QuesContent={problem}
                          ></ShowEssayQues>
                        </TouchableOpacity>
                      </View>
                    );
                  }
                  if (problem.type == 2) {
                    return (
                      <View key={index}>
                        <TouchableOpacity
                          onPress={() => {
                            t_addIndex = 1;
                            navigation.navigate("添加题目", {
                              onSubmit: onEdit,
                              type: 2,
                              quesIndex: index,
                              showQues: problem,
                            });
                          }}
                        >
                          <ShowEssayQues
                            isEdit={false}
                            number={index + 1}
                            QuesContent={problem}
                          ></ShowEssayQues>
                        </TouchableOpacity>
                      </View>
                    );
                  }
                })}
              </View>
            </ScrollView>
          </View>

          <View style={{ flex: 1 }}>
            <View style={styles.btnBox}>
              <TouchableOpacity
                style={styles.backBtn}
                onPress={() => {
                  t_addIndex = 0;
                  navigation.navigate("添加题目", {
                    onSubmit: onSubmit,
                    onDelete: onDelete,
                    isAdd: true,
                    type: 1,
                    quesIndex: -1,
                  });
                }}
              >
                <Text style={{ color: "#41C3EE" }}>添加描述问题</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.backBtn, { marginLeft: 20 }]}
                onPress={() => {
                  t_addIndex = 1;
                  navigation.navigate("添加题目", {
                    onSubmit: onSubmit,
                    onDelete: onDelete,
                    isAdd: true,
                    type: 1,
                    quesIndex: -1,
                  });
                }}
              >
                <Text style={{ color: "#41C3EE" }}>添加细节问题</Text>
              </TouchableOpacity>
            </View>
            {/* <View style={styles.btnBox}>
          <TouchableOpacity
            style={styles.backBtn}
            onPress={() => {
              navigation.goBack();
            }}
          >
            <Text style={{ color: "#41C3EE" }}>返回</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.submitBtn}
            onPress={() => {
              // addQues({ type: 0, head: groupTitle, contents: quesArr });
              navigation.goBack();
            }}
          >
            <Text style={{ color: "#fff" }}>确认</Text>
          </TouchableOpacity>
        </View> */}
          </View>
        </View>
      )}
      {problemLoading == "error" ? <Error></Error> : null}
      <Modal animationType="fade" transparent={true} visible={isEditing}>
        <Loading text="更新中"></Loading>
      </Modal>
    </View>
  );
};

var styles = StyleSheet.create({
  container: {
    // marginTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    height: "100%",
    backgroundColor: "white",
  },
  backBtn: {
    flex: 3.7,
    borderWidth: 1,
    borderColor: "#41C3EE",
    // alignContent: "center",
    // justifyContent: "center",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
  },
  submitBtn: {
    flex: 5.7,
    marginLeft: "6%",
    backgroundColor: "#41C3EE",
    alignItems: "center",
    padding: 10,
    borderRadius: 5,
  },
  btnBox: {
    flexDirection: "row",
    marginLeft: "5%",
    marginRight: "5%",
    marginTop: 10,
  },
  alterView: {
    height: "100%",
    alignItems: "center",
    justifyContent: "center",
  },
});

export default AddProblem;
